<template>
  <div class="container">
    <div class="content">
      <div class="ADClass"></div>
      <div class="login">
        <h2 class="loginTitle">合作机构服务平台</h2>
        <a-form @submit="orgSubmit" :form="orgform">
          <a-alert
            type="error"
            :closable="true"
            @close="onClose"
            v-if="errorShow"
            :message="errorMessage"
            showIcon
            style="margin-bottom: 24px"
          />
          <div style="overflow: hidden">
            <div class="labelClass">登录账号</div>
            <a-form-item>
              <a-input
                onMouseOver="this.style.borderColor='#b3292c';"
                onMouseOut="this.style.borderColor='#d9d9d9';"
                v-decorator="[
                  'orgName',
                  {
                    rules: [
                      {
                        required: true,
                        message: '请输入合作机构号',
                        whitespace: true,
                      },
                    ],
                  },
                ]"
                size="large"
                placeholder="请输入合作机构号"
              >
                <!-- {rules: [{ required: true, message: '请输入邮箱/手机号/用户名', whitespace: true},{validator: validatemail}],validateTrigger: 'blur'} -->
                <!-- <a-icon slot="prefix" type="user" /> -->
              </a-input>
            </a-form-item>
          </div>
          <div>
            <div class="labelClass">登录密码</div>
            <a-form-item>
              <a-input
                v-if="sensitive == 1"
                @change="onInputChange"
                @focus="showKeyboard"
                :maxLength="maxLength"
                onMouseOver="this.style.borderColor='#b3292c';"
                onMouseOut="this.style.borderColor='#d9d9d9';"
                v-decorator="[
                  'orgPassword',
                  {
                    rules: [
                      {
                        required: true,
                        message: '请输入密码',
                        whitespace: true,
                      },
                    ],
                  },
                ]"
                size="large"
                placeholder="请输入密码"
                type="password"
              >
                <!-- <a-icon slot="prefix" type="lock" /> -->
              </a-input>
              <a-input
                v-else
                onMouseOver="this.style.borderColor='#b3292c';"
                onMouseOut="this.style.borderColor='#d9d9d9';"
                v-decorator="[
                  'orgPassword',
                  {
                    rules: [
                      {
                        required: true,
                        message: '请输入密码',
                        whitespace: true,
                      },
                    ],
                  },
                ]"
                size="large"
                placeholder="请输入密码"
                type="password"
              >
                <!-- <a-icon slot="prefix" type="lock" /> -->
              </a-input>
            </a-form-item>
            <SimpleKeyboard
              @onChange="onChange"
              @onKeyPress="onKeyPress"
              :input="input"
              v-show="isKeyBoard"
            />
          </div>
          <div v-if="sensitive == 1">
            <a-form-item>
              <div>
                <a-input
                  class="codeinput"
                  onmouseover="this.style.borderColor='#b3292c'"
                  onmouseout="this.style.borderColor='#d9d9d9'"
                  v-decorator="[
                    'logincode',
                    {
                      rules: [
                        {
                          required: true,
                          message: '请输入验证码',
                          whitespace: true,
                        },
                      ],
                    },
                  ]"
                  size="large"
                  placeholder="请输入验证码"
                >
                </a-input>
                <a-button
                  ghost
                  class="codebutton"
                  style="border-color:#262626；color:#262626"
                  onmouseover="this.style.borderColor='#b3292c';this.style.color='#b3292c'"
                  onmouseout="this.style.borderColor='#262626';this.style.color='#262626'"
                  v-if="issend"
                  type="primary"
                  @click="getCode"
                  :loading="loading"
                  >获取验证码</a-button
                >
                <a-button
                  class="codebutton"
                  ghost
                  v-if="!issend"
                  disabled
                  type="primary"
                  >{{ count }}s后可再次发送</a-button
                >
              </div>
            </a-form-item>
          </div>
          <div id="mpanel4" style="margin-top: 35px"></div>
          <div class="sm-style">
            <!-- <a-checkbox :checked="true">自动登录</a-checkbox> -->
            <a
              style="float: right; color: #b3292c; padding-bottom: 10px"
              @click="goPassword"
              >忘记密码？</a
            >
          </div>
          <a-form-item style="margin-bottom: 0px">
            <a-button
              :loading="logging"
              style="width: 100%"
              size="large"
              htmlType="submit"
              type="primary"
              >登录
            </a-button>
          </a-form-item>
          <div class="sm-style">
            <span>&nbsp;</span>
            <!-- <router-link >&nbsp;</router-link> -->
          </div>
        </a-form>
      </div>
    </div>
  </div>
</template>


<script>
import { message } from "ant-design-vue";
import AForm from "ant-design-vue/es/form/Form";
import ATabs from "ant-design-vue/es/tabs";
import GlobalFooter from "../../layouts/GlobalFooter";
import AFormItem from "ant-design-vue/es/form/FormItem";
import AInput from "ant-design-vue/es/input/Input";
import AIcon from "ant-design-vue/es/icon";
import AInputGroup from "ant-design-vue/es/input/Group";
import AButton from "ant-design-vue/es/button/button";
import ACol from "ant-design-vue/es/grid/Col";
import ARow from "ant-design-vue/es/grid/Row";
import ACheckbox from "ant-design-vue/es/checkbox/Checkbox";
import AAlert from "ant-design-vue/es/alert/index";
import SimpleKeyboard from "../common/keyboard.vue";
import { JSEncrypt } from "jsencrypt";
import api from "@/common/api";

const ATabPane = ATabs.TabPane;

export default {
  name: "Login",
  components: {
    AAlert,
    ACheckbox,
    ACol,
    ARow,
    AButton,
    AInputGroup,
    AIcon,
    AInput,
    AFormItem,
    GlobalFooter,
    ATabPane,
    ATabs,
    AForm,
    SimpleKeyboard,
  },
  data() {
    return {
      orgform: this.$form.createForm(this),
      perform: this.$form.createForm(this),
      logging: false,
      size: "large",
      errorMessage: null,
      errorShow: false,
      slide: Boolean,
      perslide: Boolean,
      errorfun: Function,
      input: "",
      maxLength: 0,
      isKeyBoard: false,
      sensitive: localStorage.getItem("sensitive"),
      issend: true,
      timer: null,
      count: 30,
      loading: false,
    };
  },
  computed: {
    systemName() {
      return this.$store.state.setting.systemName;
    },
    linkList() {
      return this.$store.state.setting.footerLinks;
    },
    copyright() {
      return this.$store.state.setting.copyright;
    },
  },
  created() {
    sessionStorage.clear();
    localStorage.clear();
    this.getSysInfo();
    if (this.isMobile()) {
      window.location.href = "static/Mobile.html";
    }
  },
  mounted() {
    //清除SSE请求
    if (window.evtSource) {
      window.evtSource.close();
    }
    const vueself = this;
    // console.log($("#mpanel4"))
    /* eslint-disable */
    $("#mpanel4").slideVerify({
      type: 2, //类型
      vOffset: 5, //误差量，根据需求自行调整
      vSpace: 5, //间隔
      // imgName: [
      //   "image&quality=80&size=b9999_10000&sec=1558689827818&di=460971dcef166d21d211980847b0a344&imgtype=0&src=http%3A%2F%2Fwww.33lc.com%2Farticle%2FUploadPic%2F2012-7%2F201272714223895294.jpg"
      // ],
      imgName: ["img/bg.jpg", "img/KV.jpg"],
      imgSize: {
        width: "100%",
        height: "200px",
      },
      blockSize: {
        width: "40px",
        height: "38px",
      },
      barSize: {
        width: "100%",
        height: "38px",
      },
      ready: function () {
        window.slide = false;
        window.verifyrefresh = this.verifyrefresh;
      },
      success: function () {
        const self = this;
        window.slide = true;
      },
      error: function () {
        window.slide = false;
      },
      verifyrefresh: Function,
    });
  },
  watch: {
    //  function tabchange(params) {
    //  }
  },
  methods: {
    getCode() {
      let phone = this.orgform.getFieldValue("orgName");
      if (!phone) {
        this.$message.warning("请输入登陆账号！");
        return;
      }
      this.getinfocode(phone);
    },
    getinfocode(phone) {
      this.loading = true;
      const data = {
        userName: phone,
      };
      api.getlogincode(
        data,
        (res) => {
          console.log("res", res);
          if (res.code == "OK") {
            this.loading = false;
            const TIME_COUNT = 60;
            if (!this.timer) {
              this.count = TIME_COUNT;
              this.issend = false;
              this.timer = setInterval(() => {
                if (this.count > 0 && this.count <= TIME_COUNT) {
                  this.count--;
                } else {
                  this.issend = true;
                  clearInterval(this.timer);
                  this.timer = null;
                }
              }, 1000);
            }
          } else {
            this.loading = false;
            this.issend = true;
            this.$message.warning(res.message);
          }
          // console.log("res", res);
        },
        (err) => {
          this.loading = false;
          console.log(err);
        }
      );
    },
    onChange(input) {
      console.log("input", input);
      this.orgform.setFieldsValue({
        orgPassword: input,
      });
      this.input = input;
    },
    setInput(e) {
      console.log(e.target.value);
      this.input = e.target.value;
    },
    onKeyPress(button) {
      console.log("button", button);
    },
    onInputChange(input) {
      this.input = input.target.value;
    },
    showKeyboard() {
      this.isKeyBoard = true;
    },
    validatemail(rule, value, callback) {
      const reg = new RegExp(
        "^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$"
      );
      if (value && !reg.test(value)) {
        callback("您输入的邮箱格式有误！");
        return;
      } else {
        console.log(value);
        callback();
      }
    },
    orgSubmit(e) {
      e.preventDefault();
      this.orgform.validateFields((err, values) => {
        if (!err) {
          this.slide = window.slide;
          console.log(this.slide);
          if (!this.slide) {
            this.$message.warning("请滑动滑块进行验证！");
            return false;
          }
          this.logging = true;
          //获取会员公钥
          // console.log("orgName:{}", orgName);
          let username = this.orgform.getFieldValue("orgName");
          let params = { scope: "login", key: username };
          api.fetchPubKey(params, (res) => {
            console.log("res", res);
            let pass = this.orgform.getFieldValue("orgPassword");
            pass = api.getEncryptData(res.data.pubKey, pass);
            this.login(username, pass);
          });
        }
      });
    },
    login: function (username, password) {
      let data = {
        username: username,
        password: password,
        key: username,
        sensitive:this.sensitive
      };
      if(this.sensitive==1){
        data.verCode = this.orgform.getFieldValue("logincode");
      }
      this.$axios
        .post("/agent/member/login",data)
        .then((res) => {
          const result = res.data;
          console.log("res", res);
          if (result.code === "OK") {
            let token = res.headers.authorization;
            localStorage.setItem("token", token);
            localStorage.setItem("fileHostAddr", res.data.data.fileHostAddr);
            localStorage.setItem("orgType", res.data.data.orgType);
            this.$axios.defaults.headers.common["Authorization"] =
              res.headers.authorization;
            this.logging = false;

            const memberNo = result.data.memberNo;
            const mobile = result.data.mobile;
            sessionStorage.setItem("memberNo", memberNo);
            sessionStorage.setItem("mobile", mobile);

            if (res.data.data.memberType == "AGENT_MANAGER") {
              localStorage.setItem("AgentType", "AGENT_MANAGER");
              this.$router.push("/Partners/PartnersAdmin/step1");
              return false;
            } else {
              localStorage.setItem("AgentType", "");
            }
            // this.$message.info("账号正在审核中，暂不可登陆！");
            // return false;
            if (result.data.merchantAuditingStatusName == "审核通过") {
              this.$router.push("/userindex");
              // this.$router.push("/OrgRegister/step4");
            } else if (
              result.data.merchantAuditingStatusName == "提交中" ||
              result.data.merchantAuditingStatusName == "待审核" ||
              result.data.merchantAuditingStatusName == "初审不通过"
            ) {
              if (result.data.orgType == "org") {
                this.$router.push("/OrgRegister/userTypeA/step4");
              } else if (result.data.orgType == "small") {
                this.$router.push("/OrgRegister/userTypeB/step4");
              } else {
                this.$router.push("/OrgRegister/typeSelect/step4");
              }
            } else if (result.data.merchantAuditingStatusName == "初审通过") {
              this.$message.info("初审已通过，请等待复审！");
            } else if (result.data.merchantAuditingStatusName == "审核不通过") {
              this.$router.push("/OrgRegister/step4");
            } else {
              this.$router.push("/userindex");
            }
            const user = result.data;
          } else {
            this.errorMessage = result.message;
            console.log(this.errorMessage);
            if (this.errorMessage != null) {
              this.errorShow = true;
            } else {
              this.errorShow = false;
            }
            this.logging = false;
            window.verifyrefresh();
            window.slide = false;
          }
        })
        .catch((res) => {
          // console.log('error', res);
          if (res) {
            this.$message.error("连接服务器超时");
            this.logging = false;
          }
        });
    },
    getSysInfo() {
      this.$axios.get("/agent/register/getInfo").then(
        (res) => {
          console.log(res);
          if (res.data.code == "OK") {
            if (res.data.data.organ_name) {
              localStorage.setItem("sensitive", res.data.data.sensitive || "");
              localStorage.setItem("decrypt", res.data.data.decrypt);
              this.sensitive = res.data.data.sensitive || ""
            }
          }
        },
        (err) => {}
      );
    },
    handleChange(value) {
      console.log(value);
    },
    judeSubmitReceipt() {
      let data = {};
      api.judeSubmitReceipt(
        data,
        (res) => {
          if (res.code == "OK") {
            sessionStorage.setItem("isverify", true);
          } else {
            sessionStorage.setItem("isverify", false);
          }
          // this.spinning = false;
        },
        (err) => {
          console.log("err", err);
        }
      );
    },
    goPassword() {
      this.$router.push("/org/changepassword");
    },
    onClose() {
      this.errorShow = false;
    },
    isMobile() {
      var userAgentInfo = navigator.userAgent;
      console.log(userAgentInfo);
      var mobileAgents = [
        "Android",
        "iPhone",
        "SymbianOS",
        "Windows Phone",
        "iPad",
        "iPod",
      ];

      var mobile_flag = false;

      //根据userAgent判断是否是手机
      for (var v = 0; v < mobileAgents.length; v++) {
        if (userAgentInfo.indexOf(mobileAgents[v]) > 0) {
          mobile_flag = true;
          break;
        }
      }

      var screen_width = window.screen.width;
      var screen_height = window.screen.height;

      //根据屏幕分辨率判断是否是手机
      if (screen_width < 500 && screen_height < 800) {
        mobile_flag = true;
      }

      return mobile_flag;
    },
  },
};
</script>

<style scoped>
@import " ../../../static/css/color.css";

input:hover {
  border-color: #b3292c;
}

.ant-input:hover {
  border-color: #b3292c !important;
}

.ant-input:focus {
  border-color: #b3292c !important;
}

input:focus {
  border-color: #b3292c;
}

.content {
  display: flex;
  justify-content: center;
}

.ADClass {
  width: 800px;
  background-color: #b3292c;
  margin-right: 20px;
  background: url("../../../static/img/KV.jpg") no-repeat;
  /* background-size: 100% 100%; */
  border: 1px solid rgba(169, 169, 169, 0.5);
}

.login {
  width: 400px;
  padding: 30px 45px 20px 45px;
  background: rgba(169, 169, 169, 0.5);
  border: 1px solid rgba(169, 169, 169, 0.5);
  background-color: #fff;
  overflow: hidden;
  /* border-radius: 10px; */
}

.sm-style {
  height: 40px;
  line-height: 40px;
}

.tab-sty {
  width: 50%;
  text-align: center;
}

.loginTitle {
  font-size: 28px;
  margin-bottom: 30px;
  text-align: left;
}

.labelClass {
  float: left;
  margin-bottom: 5px;
  color: #93969b;
  font-size: 16px;
}
.codeinput {
  float: left;
  width: 180px;
}
.codebutton {
  border-color: #262626;
  color: #262626;
  float: left;
  margin-left: 5px;
  width: 122px;
  padding: 0px;
  height: 40px;
}
.simple-keyboard {
  width: 370px;
  margin-left: -30px;
}
</style>